<template>
  <div>
    <van-sticky>
      <van-search
        v-model="keyWord"
        show-action
        autofocus
        maxlength="30"
        shape="round"
        placeholder="请输入小说名或作者名"
        @search="onSearch"
        @cancel="onCancel"
        @clear="onClear"
      />
    </van-sticky>

    <div v-if="!isSearch">
      <div class="p-3" v-if="hotSearchList.length > 0">
        <div class="flex justify-between items-center mb-2">
          <span>热门搜索</span>
          <van-icon name="replay" size="16px" @click="handleToRefreshHotSearchList" />
        </div>
        <div class="flex flex-wrap">
          <van-tag
            @click="handleToDetail(item.id)"
            class="mr-2 mb-2"
            type="primary"
            size="medium"
            round
            v-for="item in hotSearchList"
            :key="item.id"
            >{{ item.name }}</van-tag
          >
        </div>
      </div>

      <div class="p-3" v-if="historySearchList.length > 0">
        <div class="flex justify-between items-center mb-2">
          <span>搜索历史</span>
          <van-icon name="delete" size="16px" @click="handleToClearHistorySearch" />
        </div>
        <div class="flex flex-wrap">
          <van-tag
            @click="handleToSearch(item)"
            class="mr-2 mb-2"
            color="#ebedf0"
            text-color="#323233"
            size="medium"
            round
            v-for="item in historySearchList"
            :key="item"
            >{{ item }}</van-tag
          >
        </div>
      </div>
    </div>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" v-else>
      <van-list
        class="px-4 pt-4"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <detail-card
          class="mb-4"
          v-for="item in list"
          :key="item.id"
          :id="item.id"
          :name="item.name"
          :image="item.image"
          :writer="item.writer"
          :is_over="item.is_over"
          :intro="item.intro"
          :type="item.type"
        ></detail-card>
      </van-list>
    </van-pull-refresh>
  </div>
  <BackToTop />
</template>
<script lang="ts" setup>
import { ref, Ref, onBeforeMount, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { useStore } from '@/store/index'
import { getSearch } from '@/api/homepage'
import BackToTop from '@/components/BackToTop/BackToTop.vue'
import DetailCard from '@/components/DetailCard/DetailCard.vue'
import { BookItem } from '@/common/types'

const keyWord = ref('')
const list: Ref<BookItem[]> = ref([])
const loading = ref(false)
const finished = ref(false)
const error = ref(false)
const refreshing = ref(false)

let page: number = 1
const pageSize: number = 20

const onLoad = () => {
  if (loading.value || !keyWord.value) return
  loading.value = true
  getSearch({ keyword: keyWord.value, page, pageSize })
    .then((res) => {
      if (res.data.list.length === 0) {
        finished.value = true
      }
      loading.value = false
      list.value = [...list.value, ...res.data.list]
      page += 1
    })
    .catch((e) => {
      error.value = true
    })
}
const isSearch = ref(false)
const onRefresh = () => {
  if (loading.value) return
  finished.value = false
  loading.value = true
  page = 1
  list.value = []
  getSearch({ keyword: keyWord.value, page, pageSize })
    .then((res) => {
      if (res.data.list.length === 0) {
        finished.value = true
      }
      loading.value = false
      refreshing.value = false
      list.value = [...list.value, ...res.data.list]
      page += 1
    })
    .catch((e) => {
      error.value = true
    })
}

const store = useStore()
const onSearch = () => {
  if (!keyWord.value) {
    Toast('请输入要搜索的内容')
    return
  }
  isSearch.value = true
  store.dispatch('historySearchModule/addHistoryRead', keyWord.value).then(() => {
    onRefresh()
  })
}

const router = useRouter()
const onCancel = () => {
  router.back()
}

const onClear = () => {
  isSearch.value = false
  list.value = []
  page = 1
  finished.value = false
}

const hotSearchList: Ref<BookItem[]> = ref([])
const getHotSearchList = () => {
  getSearch().then((res) => {
    hotSearchList.value = res.data.list
  })
}

const historySearchList: Ref<string[]> = computed(() => {
  return store.state.historySearchModule.historySearchList
})

const handleToClearHistorySearch = () => {
  Dialog.confirm({
    message: '确认清除搜索历史吗?'
  })
    .then(() => {
      store.dispatch('historySearchModule/clearHistoryList').then(() => {
        Toast('清除成功')
      })
    })
    .catch(() => {
      // on cancel
    })
}

const handleToDetail = (id: number) => {
  router.push({
    name: 'Detail',
    params: { id }
  })
}

const handleToSearch = (historySearchItem: string) => {
  keyWord.value = historySearchItem
  onSearch()
}

let hotSearchPage = 2
const handleToRefreshHotSearchList = () => {
  if (hotSearchPage > 10) {
    hotSearchPage = 1
  }
  getSearch({ page: hotSearchPage }).then((res) => {
    hotSearchList.value = res.data.list
  })
  hotSearchPage += 1
}

onBeforeMount(() => {
  getHotSearchList()
})
</script>
